//管理状态和业务逻辑
import { defineStore } from "pinia";
import {
  fetchShifts,
  createShift,
  updateShift,
  deleteShift,
  getShiftsByDeptId,
} from "@/api/schedule/shift";
import type { IShift } from "@/api/schedule/shift";
import { ref, computed } from "vue";
import { useUserStore } from "@/stores/modules/user";


export const useShiftStore = defineStore("shift", () => {
  const shifts = ref<IShift[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);

  const pagination = ref({
    current: 1,
    size: 10,
    total: 0,
  });

  const searchQuery = ref("");

  // 计算属性：格式化后的班次数据
  const formattedShifts = computed(() => {
  return shifts.value.map(shift => ({
    ...shift,
    startTime: shift.startTime ? shift.startTime.substring(0, 5) : '',
    endTime: shift.endTime ? shift.endTime.substring(0, 5) : '',
    workingHours: calculateWorkingHours(shift.startTime, shift.endTime)
  }));
});

  // 计算工作时长
  const calculateWorkingHours = (startTime: string, endTime: string) => {
    if (!startTime || !endTime) return 0;

    // 处理后端返回的可能带秒的时间格式 (HH:mm:ss)
    const normalizeTime = (timeStr: string) => {
      const parts = timeStr.split(':');
      return `${parts[0]}:${parts[1]}`; // 只取小时和分钟
    };

    const normStart = normalizeTime(startTime);
    const normEnd = normalizeTime(endTime);

    const [startHour, startMinute] = normStart.split(':').map(Number);
    const [endHour, endMinute] = normEnd.split(':').map(Number);

    // 计算总分钟数，处理跨天情况
    const startTotalMinutes = startHour * 60 + startMinute;
    let endTotalMinutes = endHour * 60 + endMinute;

    // 如果结束时间小于开始时间，认为是跨天班次(如夜班)
    if (endTotalMinutes < startTotalMinutes) {
      endTotalMinutes += 24 * 60; // 加24小时
    }

    const totalMinutes = endTotalMinutes - startTotalMinutes;
    return parseFloat((totalMinutes / 60).toFixed(2));
  };

  // 获取班次列表
  const getShifts = async () => {
    try {
      loading.value = true;
      error.value = null;

      const params = {
        shiftName: searchQuery.value,
        deptId :Number(useUserStore().userInfo.staff.deptId), //待修改，从pinia拿
        status: 1, // 只获取正常状态的班次
        page: pagination.value.current - 1,
        size: pagination.value.size,
      };

      const res = await fetchShifts(params);
      shifts.value = res.data.content;
      pagination.value.total = res.data.totalElements;
    } catch (err) {
      error.value = "获取班次列表失败";
      console.error("获取班次列表失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 新增班次
  const addShift = async (data: IShift) => {
    try {
      loading.value = true;
      await createShift(data);
      await getShifts();
    } catch (err) {
      console.error("新增班次失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 更新班次
  const editShift = async (data: IShift) => {
    try {
      loading.value = true;
      await updateShift(data);
      await getShifts();
    } catch (err) {
      console.error("更新班次失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 删除班次
  const removeShift = async (id: number) => {
    try {
      loading.value = true;
      await deleteShift(id);
      await getShifts();
    } catch (err) {
      console.error("删除班次失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

// 获取所有激活的班次
const fetchAllActiveShifts = async () => {
  try {
    loading.value = true;
    error.value = null;

    const deptId =  Number(useUserStore().userInfo.staff.deptId)
      
    const res = await getShiftsByDeptId(deptId);
    
    // 确保接收所有数据（根据实际API响应调整）
    shifts.value = res.data?.content || res.data || [];
    
  } catch (err) {
    error.value = "获取班次列表失败";
    throw err;
  } finally {
    loading.value = false;
  }
};

  return {
    shifts,
    formattedShifts,
    loading,
    error,
    pagination,
    searchQuery,
    getShifts,
    addShift,
    editShift,
    removeShift,
    calculateWorkingHours,
    fetchAllActiveShifts,
  };
});